﻿using AppWebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using PmSoft.ApplicationContext;
using PmSoft.Entity;

namespace AppWebApi.Authorization
{
    /// <summary>
    /// 针对App用户进行验证
    /// </summary>
    public class AppAuthorizationAttribute : Attribute, IResourceFilter
    {
        public AppAuthorizationAttribute() { }

        public AppAuthorizationAttribute(params UserType[] userTypes)
        {
            UserTypes = userTypes;
        }

        public UserType[] UserTypes { get; private set; } = new UserType[0];

        /// <summary>
        /// 请求之前
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            var applicationContext = context.HttpContext.RequestServices.GetService<IApplicationContext>();
            if (applicationContext == null)
                throw new ArgumentNullException(nameof(applicationContext));

            var userInfo = applicationContext.CurrentUser;
            if (userInfo == null || userInfo is not AppUserInfo appUserInfo)
            {
                context.Result = new JsonResult(ApiResult.Failure("请先登录").Encrypt());/* new JsonResult(ApiResult.Failure("请先登录"))*/;
                return;
            }
            else
            {
                if(UserTypes.Length > 0 && !UserTypes.Contains(userInfo.Type))
                {
                    context.Result = new JsonResult(ApiResult.Failure("当前登录信息，无权访问").Encrypt());
                    return;
                }
                if (appUserInfo.ExpireTime < DateTime.Now)
                {
                    context.Result = new JsonResult(ApiResult.Failure("身份认证过期,请重新登录").Encrypt());
                    return;
                }
            }
        }

        /// <summary>
        /// 请求之后
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            //string key = context.HttpContext.Request.Path;  //请求的路径
            //KeyValues[key] = context.Result;
        }
    }
}
